//
//  registerViewController.m
//  chatchatchat
//
//  Created by lanou3g on 16/3/23.
//  Copyright © 2016年 小灰灰. All rights reserved.
//

/* ---------- 注册界面 ---------- */

/*
 *  userInteractionEnabled 是否打开输入框
 */

#import "registerViewController.h"
#import "PrefixHeader.pch"


@interface registerViewController ()<UITextFieldDelegate>


@end

@implementation registerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"注册";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    //*** 布局注册 ***//
    [self layoutregister];
    
    //*** 布局返回按钮 ***//
    [self layoutButton];
    
    
}
//***** 布局返回按钮 *****//
- (void)layoutButton{
    //*** 返回按钮 ***//
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" style:(UIBarButtonItemStyleDone) target:self action:@selector(leftAction)];
}
//***** 返回按钮  *****//
- (void)leftAction{
    if (self.aTextField.text == nil || [self.aTextField.text isEqualToString:@""])
    {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"确定返回吗! ! !" preferredStyle:UIAlertControllerStyleAlert];

        [self presentViewController:alert animated:YES completion:^{
            
        }];
        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
        }];
        UIAlertAction *abolish = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cencel];
        [alert addAction:abolish];

    }
}
//***** 布局注册 *****//
- (void)layoutregister{
    //*** 手机号输入框 ***//
    UIView *aView = [[UIView alloc]init];
    aView.frame = CGRectMake(30, KCGFloatheight / 5 + 25, KCGFloatwidth - 60, 1);
    aView.backgroundColor = [UIColor redColor];
    [self.view addSubview:aView];
    
    self.aTextField = [[UITextField alloc]init];
    self.aTextField.frame = CGRectMake(30, KCGFloatheight / 5, KCGFloatwidth - 60, 30);
    self.aTextField.placeholder = @"请输入手机号";
    self.aTextField.keyboardType =  UIKeyboardTypeNumberPad;
    self.aTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.aTextField.delegate = self;
    [self.view addSubview:self.aTextField];
    
    //*** 验证码输入框 ***//
    UIView *bView = [[UIView alloc]init];
    bView.frame = CGRectMake(30, KCGFloatheight / 5 * 2 - 45, KCGFloatwidth / 3, 1);
    bView.backgroundColor = [UIColor redColor];
    [self.view addSubview:bView];
    
    self.bTextField = [[UITextField alloc]init];
    self.bTextField.frame = CGRectMake(30, KCGFloatheight / 5 * 2 - 70, KCGFloatwidth / 3, 30);
    self.bTextField.delegate = self;
    self.bTextField.clearsOnBeginEditing = YES;
    self.bTextField.userInteractionEnabled = NO;
    self.bTextField.keyboardType =  UIKeyboardTypeNumberPad;
    self.bTextField.placeholder = @"请输入验证码";
    [self.view addSubview:self.bTextField];
    
    //*** 布局验证码按钮 ***//
    self.aButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.aButton.frame = CGRectMake(KCGFloatwidth / 3 + 50, KCGFloatheight / 5 * 2 - 70, 150, 30);
    [self.aButton addTarget:self action:@selector(aButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.aButton setTitle:@"获取验证码" forState:(UIControlStateNormal)];
    [self.view addSubview:self.aButton];
    
    //*** 注册按钮 ***//
    self.bButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    self.bButton.frame = CGRectMake(KCGFloatwidth / 3 - 20, KCGFloatheight / 5 * 2, 150, 40);
    self.bButton.backgroundColor = [UIColor colorWithRed:0.2 green:0.3 blue:0.9 alpha:0.65];
    self.bButton.layer.cornerRadius = 5;
    [self.bButton addTarget:self action:@selector(bButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    [self.bButton setTitle:@"注册" forState:(UIControlStateNormal)];
    [self.view addSubview:self.bButton];
}
//***** 注册按钮方法 *****//
- (void)bButtonAction{
    //获取验证码输入框内容
    NSString *smsCode = self.bTextField.text;
    NSString *mobileNum = self.aTextField.text;
    
    if ((self.aTextField.text == nil || [self.aTextField.text isEqualToString:@""]) && (self.bTextField.text == nil || [self.bTextField.text isEqualToString:@""]))
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"手机号或者验证码没有填写" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
        }];
        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cencel];
    }
    else
    {
        if (smsCode.length == 6)
        {
            //*** 当输入的验证码是六位时,调用第三方方法 ***//
            
            [AVUser signUpOrLoginWithMobilePhoneNumberInBackground:mobileNum smsCode:smsCode block:^(AVUser *user, NSError *error) {
                
                if (error == nil)
                {
                    self.alertController = [UIAlertController alertControllerWithTitle:@"恭喜注册成功" message:@"(3秒之后自动返回)" preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:self.alertController animated:YES completion:^{
                        __block int timeout= 2; //倒计时时间
                        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
                        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
                        dispatch_source_set_event_handler(_timer, ^{
                            if(timeout<=0){ //倒计时结束，关闭
                                dispatch_source_cancel(_timer);
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    //*** 返回提示框 ***//
                                    [self dismissViewControllerAnimated:YES completion:nil];
                                    //*** 返回上一个界面 ***//
                                    [self dismissViewControllerAnimated:YES completion:nil];
                                });
                            }else{
                                int seconds = timeout % 3;
                                dispatch_async(dispatch_get_main_queue(), ^{
                                    //设置界面的按钮显示 根据自己需求设置
                                    self.alertController.message = [NSString stringWithFormat:@"(%d秒之后自动返回)",seconds];
                                });
                                timeout--;
                            }
                        });
                        dispatch_resume(_timer);
                    }];
                }
                else
                {
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"验证码无效,请确保验证码是在有效时间内" preferredStyle:UIAlertControllerStyleAlert];
                    [self presentViewController:alert animated:YES completion:^{
                    }];
                    UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
                    }];
                    [alert addAction:cencel];
                }
            }];
        }
    }
}
//***** 获取验证码按钮 *****//
- (void)aButtonAction{
    NSString *aTextField = self.aTextField.text;
    //*** 判断手机号不能为空 ***//
    if (self.aTextField.text == nil || [self.aTextField.text isEqualToString:@""]){
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"手机号不能为空" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
        }];
        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cencel];
    }else if(aTextField.length == 11){
        //*** 当手机号不为空,是十一位的时候,执行此 if 的方法 ***//
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"点击确定获取验证码" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
        }];
        UIAlertAction *confirm = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            [self validatePhone:self.aTextField.text];
            self.aTextField.userInteractionEnabled = NO;
            self.bTextField.userInteractionEnabled = YES;
        }];
        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            self.aTextField.userInteractionEnabled = YES;
            self.bTextField.userInteractionEnabled = NO;
        }];
        [alert addAction:cencel];
        [alert addAction:confirm];
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"注意" message:@"手机号格式不正确" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
        }];
        UIAlertAction *cencel = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        }];
        [alert addAction:cencel];
    }
}
//***** 键盘返回方法 *****//
-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event{
    [self.view endEditing:YES];
}
//***** 手机号判断 *****//
- (void)validatePhone:(NSString *)phone{
    NSString *Phone = self.aTextField.text;
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,152,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,177,180,189
     */
    NSString * MOBILE = @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
    /**
     * 中国移动：China Mobile
     * 134[0-8],135,136,137,138,139,150,151,152,157,158,159,182,187,188
     */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[0127-9]|8[278])\\d)\\d{7}$";
    /**
     * 中国联通：China Unicom
     * 130,131,132,155,156,185,186
     */
    NSString * CU = @"^1(3[0-2]|5[56]|8[56])\\d{8}$";
    /**
     * 中国电信：China Telecom
     * 133,153,180,181,189,177
     * 卫星通讯: 1349
     */
    NSString * CT = @"^1((33|53|77|8[019])[0-9]|349)\\d{7}$";
    /**
     25         * 大陆地区固话及小灵通
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     27         * 号码：七位或八位
     28         */
    // NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    if (([regextestmobile evaluateWithObject:phone] == YES) || ([regextestcm evaluateWithObject:phone] == YES) || ([regextestct evaluateWithObject:phone] == YES)
        || ([regextestcu evaluateWithObject:phone] == YES))
    {
        if([regextestcm evaluateWithObject:phone] == YES){
            NSLog(@"中国移动手机号");
        }else if([regextestct evaluateWithObject:phone] == YES){
            NSLog(@"中国电信手机号");
        }else if ([regextestcu evaluateWithObject:phone] == YES){
            NSLog(@"中国联通手机号");
        }else{
            NSLog(@"Unknow");
        }
        
        NSLog(@"手机号正确");
        //********** 注意,这是短信验证 **********//
        
        [AVOSCloud requestSmsCodeWithPhoneNumber:Phone callback:^(BOOL succeeded, NSError *error) {
            if (error)
            {
                NSLog(@"%@",error);
            }
            else
            {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"短信已发送,请注意查收" message:@"" preferredStyle:UIAlertControllerStyleAlert];
                [self presentViewController:alert animated:YES completion:^{
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self dismissViewControllerAnimated:YES completion:nil];
                    });
                }];
            }
        }];
        __block int timeout= 29; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        //每秒执行
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0);
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout <= 0){ //倒计时结束，关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self.aButton setTitle:@"重新获取验证码" forState:(UIControlStateNormal)];
                    self.aButton.backgroundColor = [UIColor whiteColor];
                    self.aButton.userInteractionEnabled = YES;
                    self.aTextField.userInteractionEnabled = YES;
                });
                
            }else{
                int seconds = timeout % 60;
                NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self.aButton setTitle:[NSString stringWithFormat:@"%@秒后再获取",strTime] forState:UIControlStateNormal];
                    self.aButton.backgroundColor = [UIColor whiteColor];
                    self.aButton.userInteractionEnabled = NO;
                });
                timeout--;
            }
        });
        dispatch_resume(_timer);
    }else{
        NSLog(@"手机号错误");
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"手机号输入错误,请输入正确手机号" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:^{
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.aTextField.userInteractionEnabled = YES;
                self.bTextField.userInteractionEnabled = NO;
                [self dismissViewControllerAnimated:YES completion:nil];
            });
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
